package com.xixilala.video.views

import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import android.view.SurfaceHolder
import android.view.SurfaceView
import com.xixilala.video.util.ImageUtil
import java.lang.Exception
import java.lang.ref.WeakReference

class ImageSurfaceView:SurfaceView, SurfaceHolder.Callback,Runnable {

    private var canvas: Canvas? = null
    private lateinit var myHolder: SurfaceHolder
    private var isDrawing = false

    private var weakBitmap: WeakReference<Bitmap>? = null

    private val paint by lazy {
        Paint()
    }

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {
        initial()
    }

    private fun initial() {
        holder.addCallback(this)
        myHolder = holder
    }

    override fun surfaceCreated(holder: SurfaceHolder) {
        isDrawing = true
        Thread(this).start()
    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {

    }

    override fun surfaceDestroyed(holder: SurfaceHolder) {
        isDrawing = false
    }

    override fun run() {

//        weakBitmap = WeakReference(ImageUtil.getAdaptedBitmap(context, measuredWidth, measuredHeight))

        while(isDrawing) {
            draw()
        }
    }

    private fun draw() {
        try {
            canvas = myHolder.lockCanvas()

            canvas?.run {

                weakBitmap?.get()?.let {
                    drawBitmap(it, 0f, 0f, paint) //todo 居中
                }

            }
        } catch (e:Exception) {
            e.printStackTrace()
        } finally {
            canvas?.let {
                myHolder.unlockCanvasAndPost(canvas)
            }
        }
    }


}